package broadcast

import (
	"errors"

	xxtea "github.com/xxtea/xxtea-go/xxtea"
)

const (
	// MsgTag 头标志
	MsgTag = 0x6279
	// XxteaKey 密钥
	XxteaKey = "6279baiyikejitest"
)

const (
	// EncryptNone 不加密
	EncryptNone = 0
	// EncryptXxtea xxtea加密
	EncryptXxtea = 1 << 0
)

// Packet 普通封包
type Packet struct {
	Data   []byte //数据
}

// EncryptByXxtea xxtea加密
func EncryptByXxtea(data []byte) []byte {

	return xxtea.Encrypt(data, []byte(XxteaKey))
}

// DecryptByXxtea xxtea解密
func DecryptByXxtea(data []byte) []byte {

	return xxtea.Decrypt(data, []byte(XxteaKey))
}

// ToByteArray 变为[]byte
func (p *Packet) ToByteArray() []byte {

	buffer := make([]byte, PacketCommandSize)

	buffer = append(buffer[0:PacketCommandSize], p.Data...)

	return buffer
}

// ToEncryptByteArray 加密
func (p *Packet) ToEncryptByteArray() ([]byte, uint8) {

	buffer := make([]byte, PacketCommandSize)


	buffer = append(buffer[0:PacketCommandSize], p.Data...)

	msgType := uint8(EncryptXxtea)

	//加密
	//xxtea
	encryptData := EncryptByXxtea(buffer)

	return encryptData, msgType
}

// ToDecryptPacket 解密
func ToDecryptPacket(data []byte, msgType uint8) (p *Packet, err error) {

	var decryptData []byte

	//xxtea
	if msgType&uint8(EncryptXxtea) != 0 {
		decryptData = DecryptByXxtea(data)
	} else if msgType == EncryptNone {
		decryptData = data
	} else {
		return nil, errors.New("Error encryption protocol")
	}

	if len(decryptData) < 4 {
		return nil, errors.New("Packet length is too short")
	}

	p = &Packet{}

	p.Data = decryptData[4:]

	return p, nil
}

// MakePacket 创建协议包
func MakePacket(mainID uint16, subID uint16, data []byte) *Packet {
	return &Packet{
		Data:   data,
	}
}
